//
//  AddBankCardVController.m
//  Experss
//
//  Created by 嗯，大葱 on 17/8/8.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "AddBankCardVController.h"
#import "AddBankCardCell.h"
#import "DLPickerView.h"

#import "BankCardListViewController.h"
#import <BRPickerView.h>
@interface AddBankCardVController ()<UITableViewDataSource, UITableViewDelegate>
{
    
    NSString *namePerson;//开户人姓名
    NSString *bankName;//开户银行
    NSString *bankAddress;//省份城市
    NSString *bankAddressDetail;//开户地址
    
    
    NSString *bankCardNum;//银行卡号
    NSString *payPassWord;//支付密码
    
    
}
@property (nonatomic, strong)NSArray *titleArray;
@property (nonatomic, strong)NSArray *titleArray2;
@property (nonatomic, strong) UITextField *addressTF;

@end

@implementation AddBankCardVController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configureNaBar];
    bankName = @"";
    _titleArray = @[@[@"开户姓名",@"开户银行",@"省份城市",@"开户地址"],@[@"银行卡号",@"支付密码"]];
    _titleArray2 = @[@[@"请输入开户姓名",@"请选择开户银行",@"请选择省份城市",@"请输入开户地址"],@[@"请输入银行卡号",@"请输入支付密码"]];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = kSpNone;
    [_tableView registerNib:[UINib nibWithNibName:@"AddBankCardCell" bundle:nil] forCellReuseIdentifier:@"AddBankCardCell"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bankNameAction:) name:@"bankNameAction" object:nil];
}

- (void)bankNameAction:(NSNotification *)notification{
   bankName = notification.userInfo[@"bankName"];
    [self.tableView reloadData];

}
    

- (void)configureNaBar {
    self.navigationItem.title = @"添加银行卡";
    //设置导航栏按钮的边距
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame= CGRectMake(0, 0, 60, 30);
    [rightBtn setImage:[UIImage imageNamed:@"all_fanhui2"] forState:(UIControlStateNormal)];
    [rightBtn addTarget:self action:@selector(handleBackAxtion) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    UIBarButtonItem *negativeSpacerleft = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacerleft.width = -20;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacerleft, btn_left, nil];
    
}

- (void)handleBackAxtion {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 4;
    }
    else {
        return 2;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *bgV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 10)];
    bgV.backgroundColor = KShouYeBg;
    return bgV;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AddBankCardCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddBankCardCell"];
    cell.selectionStyle = kSeNone;
    if (indexPath.section == 0) {
        cell.titleLB.text = _titleArray[0][indexPath.row];
        cell.conTF.placeholder = _titleArray2[0][indexPath.row];
        if (indexPath.row == 0) {
            cell.conTF.tag = 999;
            [cell.conTF addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
        }
        
        if (indexPath.row == 1 || indexPath.row == 2) {
            cell.jiantouV.hidden = NO;
            cell.conTF.userInteractionEnabled = NO;
        }
        
        
        if (indexPath.row == 1) {
            cell.conTF.text = bankName;
        }
        if (indexPath.row == 2) {
         
            cell.conTF.text = bankAddress;
        }
        if (indexPath.row == 3) {
        cell.conTF.tag = 1001;
        [cell.conTF addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
        }
        
        
    }
    if (indexPath.section == 1) {
        cell.titleLB.text = _titleArray[1][indexPath.row];
        cell.conTF.placeholder = _titleArray2[1][indexPath.row];
        if (indexPath.row == 0) {
            cell.conTF.tag = 1002;
            [cell.conTF addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
        }
        if (indexPath.row == 1) {
            cell.conTF.tag = 1003;
            [cell.conTF addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
        }
        
    }
        
  
    return cell;
}

- (void)textFieldEditChanged:(UITextField *)textFiled {
    if (textFiled.tag == 1001) {
        namePerson  = textFiled.text;
    }
    if (textFiled.tag == 1001) {
        bankAddressDetail  = textFiled.text;
    }
    if (textFiled.tag == 1002) {
        bankCardNum  = textFiled.text;
    }
    if (textFiled.tag == 1003) {
        payPassWord  = textFiled.text;
    }
}

//
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            
            BankCardListViewController *bnk = [[BankCardListViewController alloc] init];
            [self.navigationController pushViewController:bnk animated:YES];
            

        }
        
        if (indexPath.row == 2) {
            [self setupAddressTF];
        }
        
        
        
    }
}
#pragma mark - 地址 textField
- (void)setupAddressTF {
    
    [BRAddressPickerView showAddressPickerWithDefaultSelected:@[@10, @0, @3] isAutoSelect:YES resultBlock:^(NSArray *selectAddressArr) {
        bankAddress = [NSString stringWithFormat:@"%@%@%@", selectAddressArr[0], selectAddressArr[1], selectAddressArr[2]];
        //一个cell刷新
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:0];
        [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    }];

    
    
}



#pragma mark 判断银行卡号是否合法
-(BOOL)isBankCard:(NSString *)cardNumber{
    if(cardNumber.length==0){
        return NO;
    }
    NSString *digitsOnly = @"";
    char c;
    for (int i = 0; i < cardNumber.length; i++){
        c = [cardNumber characterAtIndex:i];
        if (isdigit(c)){
            digitsOnly =[digitsOnly stringByAppendingFormat:@"%c",c];
        }
    }
    int sum = 0;
    int digit = 0;
    int addend = 0;
    BOOL timesTwo = false;
    for (NSInteger i = digitsOnly.length - 1; i >= 0; i--){
        digit = [digitsOnly characterAtIndex:i] - '0';
        if (timesTwo){
            addend = digit * 2;
            if (addend > 9) {
                addend -= 9;
            }
        }
        else {
            addend = digit;
        }
        sum += addend;
        timesTwo = !timesTwo;
    }
    int modulus = sum % 10;
    return modulus == 0;
}
//确认添加银行卡
- (IBAction)sureAddBtnAction:(UIButton *)sender {
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    if (bankName.length == 0) {
        [MBProgressHUD showText:@"请输入开户姓名"];
        return;
    }
    if (bankName.length == 0) {
        [MBProgressHUD showText:@"请选择开户银行"];
        return;
    }
    if (bankAddress.length == 0) {
        [MBProgressHUD showText:@"请选择省份地址"];
        return;
    }
    if (bankAddressDetail.length == 0) {
        [MBProgressHUD showText:@"请选择开户地址"];
        return;
    }
    if ([self isBankCard:bankCardNum] == NO) {
        [MBProgressHUD showText:@"请输入正确的银行卡号"];
        return;
    }
    if (payPassWord.length == 0) {
        [MBProgressHUD showText:@"请输入支付密码"];
        return;
    }

    
    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"name":namePerson,@"bankname":bankName,@"city":bankAddress,@"address":bankAddressDetail,@"cardnum":bankCardNum,@"password":payPassWord,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    
    [HttpRequest postWithURLString:POST(Shop_PersonalAddBankCard) parameters:parameDic success:^(id responseObject) {
        
        if ([responseObject[@"ret"] intValue] != 200) {
            [MBProgressHUD showText:@"添加银行卡失败"];
            return ;
        }
        NSString *codeStr =  responseObject[@"data"][@"code"];
        if (![[NSString stringWithFormat:@"%@",codeStr] isEqualToString:@"0"]) {
            [MBProgressHUD showText:responseObject[@"data"][@"msg"]];
            return;
        }
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
    }];
}

@end
